#!/bin/bash

#全局变量
SRC_PATH=~/Src
SYS_ROOT_PATH=/opt/riscv64-glibc-gcc-thead_20200702/sysroot
CROSS_PREFIX=/opt/riscv64-glibc-gcc-thead_20200702/bin/riscv64-unknown-linux-gnu-

######################## OPEN SSL ##########################
# 版本
sll_ver=1.1.1g
# 3.0以上_用.代替
sll_ver_url=1_1_1g

#openssl 解压的目录名称
OPENSSL_PACKAGE_NAME=openssl-${sll_ver}
#openssl 压缩包名称
OPENSSL_COMPRESS_PACKAG=openssl-${sll_ver}.tar.gz

#openssl 下载链接
ssl_download_url=https://github.com/openssl/openssl/releases/download/OpenSSL_${sll_ver_url}/${OPENSSL_COMPRESS_PACKAG}

#openssl 目录
OPENSSL_SRC_PATH=${SRC_PATH}/openssl
OPENSSL_INSTALL_PATH=/opt/${OPENSSL_PACKAGE_NAME}
OPENSSL_DIR=/opt/${OPENSSL_PACKAGE_NAME}

#创建src文件夹
do_make_src_dir()
{
    if [ ! -d "${SRC_PATH}" ];then
        echo -e "\033[1;33mmkdir ${SRC_PATH} ...\033[0m"
        mkdir ${SRC_PATH}
    fi
}

#
do_download_openssl () {
    echo -e "\033[1;33mstart make and install download_openssl ...\033[0m"
    if [ ! -d "${SRC_PATH}" ] ; then
        mkdir ${SRC_PATH}
    fi
    
    if [ ! -d "${OPENSSL_SRC_PATH}" ];then
        mkdir ${OPENSSL_SRC_PATH}
    fi
    
    cd ${OPENSSL_SRC_PATH}
    
    if [ ! -f "${OPENSSL_COMPRESS_PACKAG}" ];then
        wget -c ${ssl_download_url}
    fi
    
    if [ ! -d "${OPENSSL_PACKAGE_NAME}" ];then
        tar -xf ${OPENSSL_COMPRESS_PACKAG}
    else
        rm -rf  ${OPENSSL_PACKAGE_NAME}
        tar -xf ${OPENSSL_COMPRESS_PACKAG}
    fi
    
    echo -e "\033[1;33m  done...\033[0m"
}

do_config_openssl () {
    echo -e "\033[1;33mstart make and install config ...\033[0m"
    cd ${OPENSSL_SRC_PATH}/${OPENSSL_PACKAGE_NAME}
    export CFLAGS=--sysroot=${SYS_ROOT_PATH}
    export CXXFLAGS=--sysroot=${SYS_ROOT_PATH}
    # export CNF_CFLAGS=-pthread
    # export CNF_CXXFLAGS=-std=c++11 -pthread
    ./config shared no-asm --cross-compile-prefix=${CROSS_PREFIX} --prefix=${OPENSSL_INSTALL_PATH} --openssldir=${OPENSSL_DIR}
    
    echo -e "\033[1;33m remove ${OPENSSL_SRC_PATH}/${OPENSSL_PACKAGE_NAME}/makefile -m64 ...\033[0m"
    echo -e "\033[1;33m 删除-m64 CFLAGS ...\033[0m"
    echo -e "\033[1;33m sed -i 's/-m64//g' ${OPENSSL_SRC_PATH}/${OPENSSL_PACKAGE_NAME}/Makefileg ...\033[0m"
    sed -i 's/-m64//g' ${OPENSSL_SRC_PATH}/${OPENSSL_PACKAGE_NAME}/Makefile
    echo -e "\033[1;33m  done...\033[0m"
}

do_make_openssl () {
    echo -e "\033[1;33mstart 开始编译 ...\033[0m"
    cd ${OPENSSL_SRC_PATH}/${OPENSSL_PACKAGE_NAME}
    time(make -j6 && make install -j6)
    echo -e "\033[1;33m  done...\033[0m"
}

set -e
do_make_src_dir
do_download_openssl
do_config_openssl
do_make_openssl

